using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using BusinessLayer.Model;

namespace BusinessLayer
{
    /// <summary>
    /// Implementacja serwisu odpowiadajacego za indeksowanie stron WWW
    /// </summary>
    public class IndexingService : IIndexingService
    {
        log4net.ILog log = log4net.LogManager.GetLogger("Services");

        /// <summary>
        /// Data Access Object odpowiedzialny za skladowanie danych
        /// </summary>
        protected TPBWyszukiwarkaDao dao;

        public TPBWyszukiwarkaDao Dao
        {
            get { return dao; }
            set { dao = value; }
        }

        /// <summary>
        /// Metoda dokonujaca indeksowania strony WWW
        /// </summary>
        /// <param name="url">URL zindeksowanej strony</param>
        /// <param name="content">Zawartosc strony pozbawiona znacznikow HTML</param>
        public void IndexContent(String url, String content)
        {
            log.Debug("Tworzenie indeksu dla urla: " + url);

            WebPage webPage = new WebPage(url, content);
            dao.ClearWebPageIndex(webPage);
            dao.AddWebPage(webPage);

            IDictionary<string, long> words = new Dictionary<string, long>();

            StringReader reader = new System.IO.StringReader(content);
            string word = "";
            long position = 0;
            while(reader.Peek() != -1)
            {
                char c = (char)reader.Read();
                position++;

                if (char.IsLetter(c))
                {
                    word += c;
                }
                else
                {
                    word = word.ToUpper();
                    if (word != "" && !words.ContainsKey(word))
                    {

                        words.Add(word, position - word.Length);
                    }

                    word = "";
                }
            }

            foreach (string wrd in words.Keys)
            {
                IndexElement indexElement = new IndexElement(webPage, words[wrd]);
                Word w = new Word(wrd);
                w.IndexElements.Add(indexElement);
                indexElement.Word = w;

                dao.AddWord(w);
            }
        }
    }
}
